import { useEffect, useState, useRef } from 'react'
import styles from './shopp.module.scss'
import { CloseOutline, SearchOutline } from 'antd-mobile-icons'
import { Grid, Image } from 'react-vant'
import { CartO } from '@react-vant/icons'
import { Input } from 'antd-mobile'
import mkf from '../../assets/mkf.png'
import wzky from '../../assets/wzky.png'
import { useNavigate } from 'react-router-dom'
import { getShoppMenu, getShoppSkin, getShoppPhysical, getShoppScroll, getShoppList } from '../../api/shoppService'
const Index = () => {
  const [searchValue, setSearchValue] = useState('')
  const [collapsed, setCollapsed] = useState(false)
  const [ShoppSkin, setShoppSkin] = useState<any[]>([])
  const [ShoppPhysical, setShoppPhysical] = useState<any[]>([])
  const [ShoppScroll, setShoppScroll] = useState<any[]>([])
  const [ShoppList, setShoppList] = useState<any[]>([])
  const [listPage, setListPage] = useState(1)
  const [listLoading, setListLoading] = useState(false)
  const [listHasMore, setListHasMore] = useState(true)
  const loadMoreRef = useRef<HTMLDivElement | null>(null)
  const placeholders = [
    '盐酸西替利嗪片',
    '糠酸莫米松乳膏',
    '布洛芬缓释胶囊',
    '板蓝根颗粒',
    '维生素C泡腾片'
  ]
  const nav=useNavigate()
  const [phIndex, setPhIndex] = useState(0)
  const [ShoppMenu, setShoppMenu] = useState<Array<{ image: string; name: string }>>([])
  const handleSearchChange = (value: string) => {
    setSearchValue(value)
  }
  const handleSearchSubmit = () => {
  }
  const clearSearchInput = () => {
    setSearchValue('')
  }
  useEffect(() => {
    let rafId = 0
    const COLLAPSE_OFFSET = 5
    const readScrollTop = () => {
      const w = typeof window !== 'undefined' ? window.scrollY : 0
      const de = document.documentElement ? document.documentElement.scrollTop : 0
      const bd = document.body ? document.body.scrollTop : 0
      return Math.max(w, de, bd)
    }
    const loop = () => {
      const y = readScrollTop()
      const shouldCollapse = y > COLLAPSE_OFFSET
      setCollapsed(prev => (prev !== shouldCollapse ? shouldCollapse : prev))
      rafId = requestAnimationFrame(loop)
    }
    rafId = requestAnimationFrame(loop)
    return () => cancelAnimationFrame(rafId)
  }, [])

  const getList = async () => {
    const menu = await getShoppMenu()
    setShoppMenu(menu.data.goods_category as Array<{ image: string; name: string }>)
    const Skin = await getShoppSkin()
    setShoppSkin(Skin.data.recommend_big_cards)
    const Physical = await getShoppPhysical()
    setShoppPhysical(Physical.data.recommend_small_cards)
    const Scroll = await getShoppScroll()
    setShoppScroll(Scroll.data.hot_search_key_words)
    const List = await getShoppList()
    setShoppList(List.data.content_list)

  }
  useEffect(() => {
    getList()
  }, [])
  // 轮播占位：优先使用接口 ShoppScroll；为空时回退到本地 placeholders
  useEffect(() => {
    if (searchValue) return
    const total = (Array.isArray(ShoppScroll) && ShoppScroll.length > 0)
      ? ShoppScroll.length
      : placeholders.length
    const timer = setInterval(() => {
      setPhIndex((idx) => (idx + 1) % total)
    }, 3000)
    return () => clearInterval(timer)
  }, [searchValue, ShoppScroll])

  // 当远端数据就绪或规模变化时，重置索引避免越界
  useEffect(() => {
    setPhIndex(0)
  }, [ShoppScroll])

  const getRollingText = (): string => {
    if (searchValue) return ''
    if (Array.isArray(ShoppScroll) && ShoppScroll.length > 0) {
      const raw: any = ShoppScroll[phIndex % ShoppScroll.length]
      // 兼容后端返回为字符串或对象的多种字段
      return typeof raw === 'string'
        ? raw
        : (raw?.keyword || raw?.name || raw?.title || raw?.item || '') || placeholders[phIndex % placeholders.length]
    }
    return placeholders[phIndex % placeholders.length]
  }
  const handelgocat=()=>{
   nav('/shoppcat')
  }
  const handelgodeat=(shop_spu_id:string)=>{
    console.log(shop_spu_id);
    nav(`/detail/${shop_spu_id}`)
    
  }
  return (
    <div className={styles.page}>
      <div className={`${styles.seachbox} ${collapsed ? styles.collapsed : ''}`}>
        <div className={styles.customSearch}>
          <span className={styles.searchIcon}>
            <SearchOutline />
          </span>
          {searchValue === '' && (
            <span className={styles.rollingPlaceholder} key={phIndex}>
              {getRollingText()}
            </span>
          )}
          <Input
            placeholder={''}
            className={styles.searchInput}
            value={searchValue}
            onChange={handleSearchChange}
            onEnterPress={handleSearchSubmit}
          />
          {searchValue && (
            <span className={styles.clearIcon} onClick={clearSearchInput}>
              <CloseOutline />
            </span>
          )}
          <button className={styles.searchBtn} onClick={handleSearchSubmit}>搜索</button>
        </div>
        <div className={styles.rightIcons}>
          <img src={mkf} alt="" className={styles.rightIconBtn} />
        </div>
      </div>
      <div className={styles.searchSpacer} />
      <div>
        <Grid
          className={styles.shoppGrid}
          columnNum={5}
          border={false}
          gutter={10}
        >
          {ShoppMenu.length > 0 ? (
            ShoppMenu.map((item, ind) => (
              // 每个item作为Grid的子项，共用一个Grid容器
              <Grid.Item key={ind} className={styles.grid_item}>
                <Image
                  src={item.image}
                  className={styles.grid_image}
                />
                <p>{item.name}</p>
              </Grid.Item>
            ))
          ) : (
            // 当数组为空时，显示空状态提示
            <div className="empty-state">暂无数据</div>
          )}
        </Grid>
      </div>
      <div className={styles.wz}>
        <img src={wzky} alt="" />
      </div>
      <div className={styles.userSkin}>
        {
          ShoppSkin.map((it, ind) => (
            <img src={it.img_url} alt="" key={ind} />
          ))

        }
      </div>
      <div className={styles.userPhysical}>
        {
          ShoppPhysical.map((it, ind) => (
            <img src={it.img_url} alt="" key={ind} />
          ))

        }
      </div>
      {Array.isArray(ShoppList) && ShoppList.length > 0 && (
        <div className={styles.waterfall}>
          {(ShoppList as any[]).map((it: any, ind: number) => {
            const img = it?.img_url || it?.image || it?.pic_url || it?.cover || it?.goods_image || ''
            const title = it?.name || it?.title || it?.goods_name || ''
            const price = it?.price || it?.price_text || it?.sale_price || it?.sale_price_text || ''
            return (
              <div key={ind} className={styles.waterItem} onClick={()=>handelgodeat(it.shop_spu_id)}>
                {img && <img className={styles.waterImg} src={img} alt={title} />}
                {title && (
                  <p className={styles.waterTitle}>
                    {String(it?.tag || it?.tags || '').toUpperCase().includes('OTC') && (
                      <span style={{
                        display: 'inline-block',
                        background: '#00C853',
                        color: '#fff',
                        borderRadius: '6px',
                        padding: '2px 6px',
                        fontSize: '12px',
                        marginRight: '6px',
                        verticalAlign: 'middle'
                      }}>OTC</span>
                    )}
                    {title}
                  </p>
                )}
                {(price || price === 0) && (
                  <div className={styles.waterPrice}>{typeof price === 'number' ? `¥${price}` : String(price)}</div>
                )}
              </div>
            )
          })}
        </div>
      )}
      <div className={styles.cartFloat} onClick={handelgocat}>
        <CartO className={styles.cartFloaticon}/>
      </div>
    </div>
  )
}

export default Index
